package com.bike.bikeserver.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bike.bikeserver.common.annotation.OperationLog;
import com.bike.bikeserver.common.utils.HttpContextUtils;
import com.bike.bikeserver.domain.SysLog;
import com.bike.bikeserver.mapper.SysLogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;


/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/7/20 16:01
 */
@Aspect
@Component
public class SysLogService
{
    @Autowired
    SysLogMapper sysLogMapper;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(com.bike.bikeserver.common.annotation.OperationLog)")
    public void logPointCut()
    {
    }

    //切面 配置通知
    @AfterReturning(value = "logPointCut()", returning = "returnValue")
    public void saveSysLog(JoinPoint joinPoint, Object returnValue)
    {
        //System.out.println("在切面保存日志");
        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        /*获取操作名称*/
        //获取操作名称
        OperationLog myLog = method.getAnnotation(OperationLog.class);
        if (myLog != null)
        {
            String value = myLog.value();
            sysLog.setOperationName(value.split(":")[0]);//保存获取的操作
            /*获取操作的表名*/
            sysLog.setTName(value.split(":")[1]);
        }

        /*获取操作方法名*/
        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setOperationMethod(className + "." + methodName);

        /*获取操作者ip*/
        sysLog.setOperatorIp(HttpContextUtils.getIpAddress());

        /*获取操作的参数*/
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
        String params = JSON.toJSONString(args);
        sysLog.setOperationParams(params);

        /*获取操作结果*/
        Map<String, Object> map = (Map<String, Object>) returnValue;
        JSONObject jsonObject = new JSONObject(map);
        sysLog.setOperationResult(jsonObject.getString("msg"));

        // 保存日志
        sysLogMapper.insert(sysLog);
    }
}
